﻿$(document).ready(function () {
    InitTabs();
    $("#console-nav li").first().find("a").click();

    $(".btn-parse").on("click", function(e) {
        e.preventDefault();

        var parser = $(this).data('parser');

        var consoleNav = $("#console-nav");

        var listItems = consoleNav.find("li");

        for (var i = listItems.length - 1; i > 0; i--) {
            $("#console-nav li").eq(i).remove();
        }

        if (parser == 'ToWiki') {
            consoleNav.append("<li><a href=\"#\" data-target=\"panel-content-wiki\">Wiki</a></li>");
        }
        else if (parser == 'ToHtml') {
            consoleNav.append("<li><a href=\"#\" data-target=\"panel-content-html\">HTML</a></li>");
        }
        
        consoleNav.append("<li><a href=\"#\" data-target=\"panel-content-preview\"><span class=\"glyphicon glyphicon-search\"></span> Preview</a></li>");
        consoleNav.append("<li><a href=\"#\" data-target=\"panel-content-download\"><span class=\"glyphicon glyphicon-cloud-download\"></span> Download</a></li>");

        InitTabs();
    });

    $('#source-upload-control').bootstrapFileInput();
    $('#source-upload-control').on('change', function (e) {
        e.stopPropagation();
        e.preventDefault();

        var sourceFile = e.target.files[0];
        var data = new FormData();
        data.append('sourceFile', sourceFile);

        $.ajax({
            url: $(this).data('action'),
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
            success: function (data, textStatus, jqXHR) {
                if (data.IsValid == true) {
                    $("#source-text-area").val(data.SourceText);
                } else {
                    alert("Invalid file.");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // Handle errors here
                console.log('ERRORS: ' + textStatus);
                // STOP LOADING SPINNER
            }
        });
    });
});

function InitTabs() {
    $("#console-nav a").on("click", function (e) {
        e.preventDefault();
        $("#console-nav li").removeClass("active");
        $(this).parent().addClass("active");

        var targetDivId = $(this).data("target");
        $('#panel-content').fadeOut("fast", function () {
            $(this).html($("#" + targetDivId).html());
            $('#panel-content').fadeIn("fast");
        });
    });

    $("#console-nav").find("a")[0].click();
}